package com.tangbuzhi.flyweight;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 享元模式案例
 */
public class FlyWeightCase {
    public interface Ticket {
        void showTicketInfo(String bunk);
    }

    public static class TrainTicket implements Ticket {
        String from, to, bunk;
        int price;

        public TrainTicket(String from, String to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public void showTicketInfo(String bunk) {
            price = new Random().nextInt(300);
            System.out.println("购买从" + from + "到" + to + "的" + bunk + "火车票，价格" + price + "元");
        }
    }

    public static class TicketFactory {
        //这种做法是极其危险的，如果短时间内有10000人要购from-to的票，会造成大量重复对象的创建，GC对这些对象的回收会很耗资源。
        //如果用户量更大，意味着请求量更大，很可能导致系统变得极其缓慢，甚至可能导致OOM
        public Ticket getTicketInfo(String from, String to) {
            return new TrainTicket(from, to);
        }

        //使用享元模式修改一下，加入缓存容器
        private static Map<String, Ticket> stringTicket = new ConcurrentHashMap<>();

        public static Ticket getTicket(String from, String to) {
            Ticket ticket;
            String key = from + "-" + to;
            if (stringTicket.containsKey(key)) {
                System.out.println("使用缓存 ===>" + key);
                ticket = stringTicket.get(key);
            } else {
                System.out.println("创建对象 ===>" + key);
                ticket = new TrainTicket(from, to);
                stringTicket.put(key, ticket);
            }
            return ticket;
        }
    }

    public static void main(String[] args) {
        Ticket ticket0 = TicketFactory.getTicket("杭州", "南京");
        ticket0.showTicketInfo("坐票");

        Ticket ticket1 = TicketFactory.getTicket("杭州", "南京");
        ticket1.showTicketInfo("站票");

        Ticket ticket2 = TicketFactory.getTicket("杭州", "南京");
        ticket2.showTicketInfo("软卧");
        /**
         创建对象 ===>杭州-南京
         购买从杭州到南京的坐票火车票，价格12元
         使用缓存 ===>杭州-南京
         购买从杭州到南京的站票火车票，价格297元
         使用缓存 ===>杭州-南京
         购买从杭州到南京的软卧火车票，价格30元
         */
    }
}
